package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.service.AllServiceStationService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Service("AllServiceStationService")
public class AllServiceStationServiceImpl implements AllServiceStationService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Autowired
    private AllServiceStationDao allServiceStationDao;

    @Autowired
    private PropertiesUtils propertiesUtils;

    @Autowired
    private ThreeServiceStationDao threeServiceStationDao;

    @Resource
    private LoginDao loginDao;

    @Resource
    private SSHasSMNDao ssHasSMNDao;

    @Resource
    private WorkOrderTDao workOrderTDao;

    @Resource
    private SSRepairTDao ssRepairTDao;

    @Resource
    private ServiceStationDao serviceStationDao;


    @Resource
    private StationAndCrmStationDifferentRecordsTMapper stationAndCrmStationDifferentRecordsTMapper;

    public ModelAndView getAllServiceStation(Map<String, Object> map) {

        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        try {
            if (map.get("StationName") != null && !map.get("StationName").toString().equals("")) {
                map.put("StationName", "%" + map.get("StationName") + "%");
            }
            // 根据App传入字段UserId查询user_T表ID
            String userid = MapUtils.getString(map, "UserId");
            UserT userByid = loginDao.getUserByid(userid);
            long id = userByid.getId();
            String userPhone = userByid.getPhone();
            map.put("UserID", id);
            map.put("UserPhone", userPhone);
            // 用户经度
            String userPositionLon = MapUtils.getString(map, "PositionLon");
            // 用户纬度
            String userPositionLat = MapUtils.getString(map, "PositionLat");
            // 用户经纬度
            String endLonLat = userPositionLon + "," + userPositionLat;
            //岗位标识，1-区域服务经理；2-商务处主任(6.22新增)（非必填字段，如果是null，则默认是1）
            Integer level = MapUtils.getInteger(map, "Level");
            if (level == null) {
                level = 1;
                map.put("Level", level);
            }

            // 分页信息
            int page = 1;
            if (map.get("page") != null) {
                page = MapUtils.getInteger(map, "page", 1);
            }
            int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
            map.put("start", (page - 1) * pagesize);
            map.put("pagesize", pagesize);

            List<Map<String, Object>> serviceStationInfos = new ArrayList<>();
            if (map.get("StationName") != null && !map.get("StationName").toString().equals("")) {
                // 根据服务站名字模糊搜索
                serviceStationInfos = allServiceStationDao.getSearchServiceStationId(map);
            } else {
                // 根据UserID和服务渠道id查询该区域服务经理下的服务站ID
                serviceStationInfos = allServiceStationDao.getServiceStationId(map);
            }

            /**
             * 判断总条数 ==0 返回错误信息 !=0 判断当前页是否有数据 无 返回空数组 有 返回数据
             */
            if (serviceStationInfos.size() == 0 && page == 1) {
                JSONObject obj = new JSONObject();
                try {
                    obj.put("status", 0);
                    obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-19));
                    obj.put("data", new JSONObject().put("allServiceStationList", new JSONArray()));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                ParameterTool.writeResponse(response, obj.toString());

            } else {
                if (serviceStationInfos.size() > 0) {

                    List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();

                    for (int ssIndex = 0; ssIndex < serviceStationInfos.size(); ssIndex++) {

                        Map<String, Object> cerT = serviceStationInfos.get(ssIndex);


                        Map<String, Object> paramMap = new HashMap<String, Object>();

                        int ss = MapUtils.getIntValue(cerT, "SSType");
                        int ssl = MapUtils.getIntValue(cerT, "SSLevel");
                        map.put("ss", ss);
                        map.put("ssl", ssl);
                        Map<String, Object> ssType = threeServiceStationDao.getSSType(map);
                        Map<String, Object> ssLevel = threeServiceStationDao.getSSLevel(map);
                        if (ssType != null) {
                            String[] sstypes = ssType.get("DValue").toString().split(",");
                            paramMap.put("SSType", sstypes);
                        } else {
                            String[] sstypes = "维护保养".split(",");
                            paramMap.put("SSType", sstypes);
                        }
                        if (ssLevel != null) {
                            String[] ssLevels = ssLevel.get("DValue").toString().split(",");
                            paramMap.put("SSLevel", ssLevels);
                        } else {
                            String[] ssLevels = "其他".split(",");
                            paramMap.put("SSLevel", ssLevels);
                        }
                        paramMap.put("serviceStationId", cerT.get("ID"));
                        paramMap.put("serviceSite", cerT.get("StationName"));
                        paramMap.put("telephone", cerT.get("HotlineTel"));
                        paramMap.put("address", cerT.get("Address"));
                        paramMap.put("longitude", cerT.get("PositionLon"));
                        paramMap.put("latitude", cerT.get("PositionLat"));
                        String distanceStr = String.format("%.2f", Double.valueOf(cerT.get("distance").toString()));
                        paramMap.put("distance", distanceStr + "km");
                        //业务上ChannelId-渠道必传，3-DCEC渠道
                        if ("3".equals(MapUtils.getString(map, "ChannelId"))) {
                            paramMap.put("requestStatus", MapUtils.getString(cerT, "RequestStatus", ""));
                        }
                        paramList.add(paramMap);
                    }

                    JSONObject obj = new JSONObject();
                    net.sf.json.JSONArray jsonArr = new net.sf.json.JSONArray();
                    if (paramList != null && paramList.size() > 0) {
                        jsonArr = net.sf.json.JSONArray.fromObject(paramList);
                    }
                    try {
                        obj.put("status", 0);
                        obj.put("msg", "");
                        obj.put("data", new JSONObject().put("allServiceStationList", jsonArr));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ParameterTool.writeResponse(response, obj.toString());

                } else {
                    JSONObject obj = new JSONObject();
                    JSONArray jsonArr = new JSONArray();
                    try {
                        obj.put("status", 0);
                        obj.put("msg", "");
                        obj.put("data", new JSONObject().put("allServiceStationList", jsonArr));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    ParameterTool.writeResponse(response, obj.toString());
                }
            }
        } catch (Exception ex) {
            // TODO: handle exception
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
            // 主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }


    //DBU区域工程师获取推荐三家服务站+管辖下所有服务站    分页
    @Transactional
    @Override
    public ModelAndView getDBUAllServiceStation(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        try {
            JSONObject obj = new JSONObject();   //返给手机端数据容器
            if (!map.containsKey("OrderId")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "服务工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            if (!map.containsKey("PositionLon")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "经度不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            if (!map.containsKey("PositionLat")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "纬度不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            int pageNo = MapUtils.getIntValue(map, "pageNo", 1);
            int pageSize = MapUtils.getIntValue(map, "pageSize", 20);
            long orderId = Long.parseLong(map.get("OrderId").toString());  //服务工单id
            float positionLon = Float.parseFloat(map.get("PositionLon").toString());//故障点经度
            float positionLat = Float.parseFloat(map.get("PositionLat").toString());//故障点纬度
            String stationName = MapUtils.getString(map, "stationName", "");
            //根据工单id获取CAC审核通过工单后同步的服务站相关数据
            Map<String, Object> recommendThreeStationMap = allServiceStationDao.getRecommendThreeStationForDBUByOrderId(orderId);
            String userPhone = "";
            if (MapUtils.isNotEmpty(recommendThreeStationMap)) {
                userPhone = recommendThreeStationMap.get("DBEngineerPhone").toString();
            }
//            long firstStationId = MapUtils.getLongValue(recommendThreeStationMap, "FirstStationId", 0);
//            long secondStationId = MapUtils.getLongValue(recommendThreeStationMap, "SecondStationId", 0);
//            long thirdStationId = MapUtils.getLongValue(recommendThreeStationMap, "ThirdStationId", 0);
            Map<String, Object> hashMap = new HashMap<>(map);
            hashMap.put("userPhone", userPhone);
            //sprint27   根据SMN查询服务站
//            String smn = MapUtil.getMapValue(map, "SMN");
            if (map.containsKey("SMN")) {
                hashMap.put("SMN", MapUtil.getMapValue(map, "SMN"));
            }
            //查询区域工程师所在区域下的所有服务站（即该CSH下的所有服务站）
            //3.5.0需求
            List<Map<String, Object>> serviceStationList = getAllServiceStationList(orderId, hashMap);
            //获取CAC推荐的三家服务站   放在集合最前    后面拼接区域工程师所在区域下所有服务站 3.5.0之前的需求
//            List<Map<String, Object>> serviceStationList = allServiceStationDao.getServiceStationListByAreaEngineer(orderId, userPhone, positionLat, positionLon, pageNo, pageSize, stationName);

            if (CollectionUtils.isNotEmpty(serviceStationList)) {
                for (Map<String, Object> serviceStation : serviceStationList) {
                    long serviceStationId = MapUtils.getLongValue(serviceStation, "serviceStationId");
                    int isRecommendServiceStation = 0;    //1：是     0 ：否    默认否
//                    if (serviceStationId == firstStationId || serviceStationId == secondStationId || serviceStationId == thirdStationId) {
//                        isRecommendServiceStation = 1;
//                    }
                    serviceStation.put("isRecommendServiceStation", isRecommendServiceStation);
                    String ssType = serviceStation.get("SSType").toString();
                    String[] ssTypeSZ = new String[1];
                    if ("1".equals(ssType)) {
                        ssTypeSZ[0] = "维护保养";
                    } else if ("2".equals(ssType)) {
                        ssTypeSZ[0] = "保养及外围件维修";
                    } else if ("3".equals(ssType)) {
                        ssTypeSZ[0] = "全职";
                    } else {
                        ssTypeSZ[0] = "";
                    }
                    String[] ssLevelSZ = new String[1];
                    ssLevelSZ[0] = "其他";
                    serviceStation.put("SSType", ssTypeSZ);
                    serviceStation.put("SSLevel", ssLevelSZ);
                    //截取距离   保留小数点后一位
                    String distance = serviceStation.get("distance").toString();
                    distance = distance.substring(0, distance.indexOf(".") + 2) + "km";
                    serviceStation.put("distance", distance);
                    List<SSHasSMN> smnListByStationId = ssHasSMNDao.getSMNListByStationId(serviceStationId);
                    String smn = "";
                    if (CollectionUtils.isNotEmpty(smnListByStationId)) {
                        if (CollectionUtils.isNotEmpty(smnListByStationId)) {
                            List<String> collect = smnListByStationId.stream().map(SSHasSMN::getServiceModelName).collect(Collectors.toList());
                            smn = collect.toString().substring(1, collect.toString().length() - 1);
                        }
                    }
                    serviceStation.put("SMN", smn);
                }
            }
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("allServiceStationList", serviceStationList);
            obj.put("data", returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception e) {
            ParameterTool.writeErrorResponse(response);
            //主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage(), e);
        }
        return null;
    }


    //区域工程师获取获取   crm 推荐的服务站
    @Override
    public ModelAndView getCrmDBUAllServiceStation(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        UserT userT = UserThreadLocal.get();
        try {
            JSONObject obj = new JSONObject();   //返给手机端数据容器
            if (!map.containsKey("OrderId")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "服务工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            //查询服务站的
            Long orderId = Long.valueOf(map.get("OrderId").toString());
            WorkOrderT workOrder = workOrderTDao.getWorkOrderByOrderId(orderId);
            if (null == workOrder) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "服务工单id不正确");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }

            //调用 crm 获取服务站 列表
            CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().getStationListByCrm(workOrder.getOrderNoCrm());
//            CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().getStationListByCrm("00166431");//测试数据
            if (cRMResponeEntity.getStatus() != 0) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "获取数据失败");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            net.sf.json.JSONObject data = cRMResponeEntity.getData();
            //将数据进行封装
            Object object = data.get("data");
            com.alibaba.fastjson.JSONArray objects = com.alibaba.fastjson.JSONObject.parseArray(object.toString());
            List<String> stringList = new ArrayList<>();//crm同步过来的数据；
            Map<String, Double> stringMap = new HashedMap<>(); // key为 MovexId，value为距离
            Map<String, String> movexIdMap = new HashedMap<>(); // key为 MovexId，value为距离
            for (Object o : objects) {
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(o.toString());
                Double distance = jsonObject.getDouble("distance");
                com.alibaba.fastjson.JSONObject jsonMove = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.get("dealer").toString());
                String movexId = jsonMove.getString("MovexId__c");
                stringList.add(movexId);
                stringMap.put(movexId, distance);
                movexIdMap.put(movexId, com.alibaba.fastjson.JSONObject.parseObject(o.toString()).toJSONString());
            }
            if (CollectionUtils.isEmpty(stringList)) {
                obj.put("data", new HashMap<>());
                obj.put("status", 0);
                obj.put("msg", "success");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            //根据 MovexId  同  BusinessNo  做比较
            List<SSRepairT> ssRepairTByBusinessNos = ssRepairTDao.getSSRepairTByBusinessNos(stringList);
            if (CollectionUtils.isEmpty(ssRepairTByBusinessNos)) {
                //记录数据
                Set<String> strings = movexIdMap.keySet();
                //crm的服务站没在app中的做记录，全部记录
                for (String string : strings) {
                    StationAndCrmStationDifferentRecordsT stationDifferentRecordsT = new StationAndCrmStationDifferentRecordsT();
                    stationDifferentRecordsT.setOrderID(orderId);
                    String str = movexIdMap.get(string);
                    stationDifferentRecordsT.setCrmStationDetail(str);
                    stationDifferentRecordsT.setMovexId(string);
                    stationDifferentRecordsT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    stationDifferentRecordsT.setCreator(userT.getId());
                    stationAndCrmStationDifferentRecordsTMapper.insert(stationDifferentRecordsT);
                }
                obj.put("data", new HashMap<>());
                obj.put("status", 0);
                obj.put("msg", "success");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            //crm的服务站没在app中的做记录
            if (objects.size() != ssRepairTByBusinessNos.size()) {
                List<String> collect = ssRepairTByBusinessNos.stream().map(SSRepairT::getBusinessno).collect(Collectors.toList());
                Set<String> strings = stringMap.keySet();
                for (String string : strings) {
                    if (!collect.contains(string)) {
                        //记录数据
                        StationAndCrmStationDifferentRecordsT stationDifferentRecordsT = new StationAndCrmStationDifferentRecordsT();
                        stationDifferentRecordsT.setOrderID(orderId);
                        String str = movexIdMap.get(string);
                        stationDifferentRecordsT.setCrmStationDetail(str);
                        stationDifferentRecordsT.setMovexId(string);
                        stationDifferentRecordsT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                        stationDifferentRecordsT.setCreator(userT.getId());
                        stationAndCrmStationDifferentRecordsTMapper.insert(stationDifferentRecordsT);
                    }
                }
            }
            String stationName = MapUtils.getString(map, "stationName", "");
            List<Long> stations = ssRepairTByBusinessNos.stream().map(SSRepairT::getServicestationid).collect(Collectors.toList());
            List<Map<String, Object>> normalServiceStationDetailList = allServiceStationDao.getServiceStationNoLon(stations, stationName);
            log.info("CSH下所有服务站列表：" + JsonUtils.toJsonString(normalServiceStationDetailList));

//        //手动分页

            //过滤smn
            List<Map<String, Object>> listadd = new ArrayList<>();
            if (map.containsKey("SMN")) {
                List<Long> stationList = null;
                String smn = workOrder.getSMN();
                if (StringUtils.isNotBlank(smn)) {
                    stationList = ssHasSMNDao.getServiceStationListBySMN(smn);
                }
                if (!CollectionUtils.isEmpty(stationList)) {
                    for (Map<String, Object> objectMap : normalServiceStationDetailList) {
                        Long serviceStationId = (Long) objectMap.get("serviceStationId");
                        if (stationList.contains(serviceStationId)) {
                            listadd.add(objectMap);
                        }
//                        if (!stationList.contains(serviceStationId)) {
//                            normalServiceStationDetailList.remove(objectMap);
//                        }
                    }
                } else {
                    normalServiceStationDetailList = new ArrayList<>();
                }
                normalServiceStationDetailList = listadd;
            }

            int pageNo = MapUtils.getIntValue(map, "pageNo", 1);
            int pageSize = MapUtils.getIntValue(map, "pageSize", 20);
            if ((long) (pageNo - 1) * pageSize > normalServiceStationDetailList.size()) {
                normalServiceStationDetailList = new ArrayList<>();
            } else if ((long) (pageNo - 1) * pageSize < normalServiceStationDetailList.size() - pageSize) {
                normalServiceStationDetailList = normalServiceStationDetailList.subList((pageNo - 1) * pageSize, (pageNo - 1) * pageSize + pageSize);
            } else {
                normalServiceStationDetailList = normalServiceStationDetailList.subList((pageNo - 1) * pageSize, normalServiceStationDetailList.size());
            }


            if (CollectionUtils.isNotEmpty(normalServiceStationDetailList)) {
                for (Map<String, Object> serviceStation : normalServiceStationDetailList) {
                    long serviceStationId = MapUtils.getLongValue(serviceStation, "serviceStationId");
                    int isRecommendServiceStation = 0;    //1：是     0 ：否    默认否
                    serviceStation.put("isRecommendServiceStation", isRecommendServiceStation);
                    String ssType = serviceStation.get("SSType").toString();
                    String[] ssTypeSZ = new String[1];
                    if ("1".equals(ssType)) {
                        ssTypeSZ[0] = "维护保养";
                    } else if ("2".equals(ssType)) {
                        ssTypeSZ[0] = "保养及外围件维修";
                    } else if ("3".equals(ssType)) {
                        ssTypeSZ[0] = "全职";
                    } else {
                        ssTypeSZ[0] = "";
                    }
                    String[] ssLevelSZ = new String[1];
                    ssLevelSZ[0] = "其他";
                    serviceStation.put("SSType", ssTypeSZ);
                    serviceStation.put("SSLevel", ssLevelSZ);
                    //截取距离   保留小数点后一位
                    String businessNo = serviceStation.get("BusinessNo").toString();
                    String distance = "";
                    if (stringMap.containsKey(businessNo)) {
                        if (null != stringMap.get(businessNo)) {
                            distance = stringMap.get(businessNo).toString() + "km";
                        } else {
                            distance = 999 + "km";
                        }
                        serviceStation.put("sortNum", stringMap.get(businessNo));
                    }
                    serviceStation.put("distance", distance);
                    List<SSHasSMN> smnListByStationId = ssHasSMNDao.getSMNListByStationId(serviceStationId);
                    String smn = "";
                    if (CollectionUtils.isNotEmpty(smnListByStationId)) {
                        List<String> collect = smnListByStationId.stream().map(SSHasSMN::getServiceModelName).collect(Collectors.toList());
                        smn = collect.toString().substring(1, collect.toString().length() - 1);
                    }
                    serviceStation.put("SMN", smn);
                }
            }
            //排序
            normalServiceStationDetailList = normalServiceStationDetailList.stream().sorted((e1, e2) ->
                    ((Double) e1.get("sortNum")).compareTo((Double) e2.get("sortNum"))
            ).collect(Collectors.toList());
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("allServiceStationList", normalServiceStationDetailList);
            obj.put("data", returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception e) {
            ParameterTool.writeErrorResponse(response);
            log.error(e.getMessage(), e);
        }
        return null;
    }


    @Override
    public ModelAndView getCrmAndLocalStations(Map<String, Object> map) {
        Integer type = MapUtils.getInteger(map, "type");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        JSONObject obj = null;
        try {
            if (type == null) {
                obj = new JSONObject();
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "服务工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
            }
            if (type == 0) {
                this.getDBUAllServiceStation(map);
            } else if (type == 1) {
                this.getCrmDBUAllServiceStation(map);
            } else {
                obj = new JSONObject();
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "请输入type");
                ParameterTool.writeResponse(response, obj.toString());
            }
        } catch (Exception e) {
            ParameterTool.writeErrorResponse(response);
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public JSONObject getChildrenServiceStation(Long ServiceStationId, String StationName, String PositionLon, String PositionLat, Long ChannelId) {
        JSONObject obj = new JSONObject();
        List<Map<String, Object>> serviceStationInfos = serviceStationDao.querychildrenStationInfo(ServiceStationId, StationName, PositionLon, PositionLat);
        if (serviceStationInfos.size() > 0) {
            List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();
            for (int ssIndex = 0; ssIndex < serviceStationInfos.size(); ssIndex++) {
                Map<String, Object> cerT = serviceStationInfos.get(ssIndex);
                Map<String, Object> paramMap = new HashMap<String, Object>();
                Map<String, Object> queryMap = new HashMap<String, Object>();
                int ss = MapUtils.getIntValue(cerT, "SSType");
                int ssl = MapUtils.getIntValue(cerT, "SSLevel");
                queryMap.put("ss", ss);
                queryMap.put("ssl", ssl);
                Map<String, Object> ssType = threeServiceStationDao.getSSType(queryMap);
                Map<String, Object> ssLevel = threeServiceStationDao.getSSLevel(queryMap);
                if (ssType != null) {
                    String[] sstypes = ssType.get("DValue").toString().split(",");
                    paramMap.put("SSType", sstypes);
                } else {
                    String[] sstypes = "维护保养".split(",");
                    paramMap.put("SSType", sstypes);
                }
                if (ssLevel != null) {
                    String[] ssLevels = ssLevel.get("DValue").toString().split(",");
                    paramMap.put("SSLevel", ssLevels);
                } else {
                    String[] ssLevels = "其他".split(",");
                    paramMap.put("SSLevel", ssLevels);
                }
                paramMap.put("serviceStationId", cerT.get("ID"));
                paramMap.put("serviceSite", cerT.get("StationName"));
                paramMap.put("telephone", cerT.get("HotlineTel"));
                paramMap.put("address", cerT.get("Address"));
                paramMap.put("longitude", cerT.get("PositionLon"));
                paramMap.put("latitude", cerT.get("PositionLat"));
                String distanceStr = String.format("%.2f", Double.valueOf(cerT.get("distance").toString()));
                paramMap.put("distance", distanceStr + "km");
                //业务上ChannelId-渠道必传，3-DCEC渠道
                if ("3".equals(ChannelId)) {
                    paramMap.put("requestStatus", MapUtils.getString(cerT, "RequestStatus", ""));
                }
                paramList.add(paramMap);
            }
            com.alibaba.fastjson.JSONArray jsonArr = new com.alibaba.fastjson.JSONArray();
            if (paramList != null && paramList.size() > 0) {
                jsonArr = com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(paramList, SerializerFeature.WriteMapNullValue));
            }
            try {
                obj.put("status", 0);
                obj.put("msg", "");
                obj.put("data", new JSONObject().put("allServiceStationList", jsonArr));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return obj;

        } else {
            JSONArray jsonArr = new JSONArray();
            try {
                obj.put("status", 0);
                obj.put("msg", "");
                obj.put("data", new JSONObject().put("allServiceStationList", jsonArr));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return obj;
        }
    }


    /**
     * sprint 3.5.0需求：需要该区域工程师在指派服务站时能够看到该CSH下所有服务站列表
     *
     * @param orderId 服务工单编号
     * @return List
     * @author Disey
     * @since 2021-09-26
     */
    private List<Map<String, Object>> getAllServiceStationList(Long orderId, Map<String, Object> map) {
        String userPhone = MapUtils.getString(map, "userPhone");
        Float positionLat = MapUtils.getFloat(map, "PositionLat");
        Float positionLon = MapUtils.getFloat(map, "PositionLon");
        String stationName = MapUtils.getString(map, "stationName", "");
        log.info("区域工程师获取服务站列表：" + "工单Id:" + orderId);
        //查询所有服务站id
//        List<Map<String, Object>> allServiceStationInCSH = allServiceStationDao.getAllServiceStationInCSH(orderId);
        UserT userT = UserThreadLocal.get();
        List<Map<String, Object>> allServiceStationInCSH = allServiceStationDao.getAllServiceStationInCSHNew(userT.getPhone());
        //查询推荐服务网站详细信息
//        List<Map<String, Object>> recommendServiceStationList = allServiceStationDao.getRecommendedServiceStationDetail(orderId, userPhone,positionLat,positionLon,stationName);
        List<Map<String, Object>> recommendServiceStationList = new ArrayList<>();
        List<Long> serviceStationIds = new ArrayList<>();
        Set<Map<String, Object>> set = new LinkedHashSet<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<Long, Object> dicMap = new LinkedHashMap<>();
        if (CollectionUtils.isEmpty(allServiceStationInCSH) && CollectionUtils.isEmpty(recommendServiceStationList)) {
            return new ArrayList<>();
        } else {
            log.info("推荐服务站列表：" + JsonUtils.toJsonString(recommendServiceStationList));
            if (CollectionUtils.isNotEmpty(recommendServiceStationList)) {
//                set.addAll(recommendServiceStationList);
                //去重
                for (Map<String, Object> stringObjectMap : recommendServiceStationList) {
                    Long serviceStationId = (Long) stringObjectMap.get("serviceStationId");
                    dicMap.put(serviceStationId, stringObjectMap);
                }
                log.info("推荐服务站列表去重排序后：" + JsonUtils.toJsonString(set));
            }
            if (CollectionUtils.isNotEmpty(allServiceStationInCSH)) {
                allServiceStationInCSH.forEach(m -> {
                    serviceStationIds.add(MapUtils.getLong(m, "ServiceStationID"));
                });
                List<Map<String, Object>> normalServiceStationDetailList = allServiceStationDao.getServiceStationDetail(serviceStationIds, positionLat, positionLon, stationName);
                log.info("CSH下所有服务站列表：" + JsonUtils.toJsonString(normalServiceStationDetailList));
//                set.addAll(normalServiceStationDetailList);
                Map<Long, Object> dicMapNor = new LinkedHashMap<>();
                for (Map<String, Object> stringObjectMap : normalServiceStationDetailList) {
                    Long serviceStationId = (Long) stringObjectMap.get("serviceStationId");
                    Integer SSType = (Integer) stringObjectMap.get("SSType");
                    if (!dicMap.containsKey(serviceStationId)) {
                        if (dicMapNor.containsKey(serviceStationId)) {
                            Map<String, Object> objectMap = (Map<String, Object>) dicMapNor.get(serviceStationId);
                            Integer ssTypeObj = (Integer) objectMap.get("SSType");
                            if (ssTypeObj < SSType) {
                                dicMapNor.put(serviceStationId, stringObjectMap);
                            }
                        } else {
                            dicMapNor.put(serviceStationId, stringObjectMap);
                        }
                    }

                }
                if (!dicMapNor.isEmpty()) {
                    dicMap.putAll(dicMapNor);
                }
            }
//            list.addAll(set);
            Set<Long> strings = dicMap.keySet();
            Iterator<Long> iterator = strings.iterator();
            ///spring27   根据smn  查询服务站；
            String smn = MapUtil.getMapValue(map, "SMN");
            if (map.containsKey("SMN")) {
                List<Long> stationList = null;
                if (StringUtils.isNotBlank(smn)) {
                    stationList = ssHasSMNDao.getServiceStationListBySMN(smn);
                }
                while (iterator.hasNext()) {
                    Long next = iterator.next();
                    Map<String, Object> mapVo = (Map<String, Object>) dicMap.get(next);
                    Long serviceStationId = (Long) mapVo.get("serviceStationId");
                    if (CollectionUtils.isEmpty(stationList)) {
//                    list.add(mapVo);
                        break;
                    } else {
                        if (stationList.contains(serviceStationId)) {
                            list.add(mapVo);
                        }
                    }
                }
            } else {
                while (iterator.hasNext()) {
                    Long next = iterator.next();
                    Map<String, Object> mapVo = (Map<String, Object>) dicMap.get(next);
                    list.add(mapVo);
                }
            }
            //手动分页
            int pageNo = MapUtils.getIntValue(map, "pageNo", 1);
            int pageSize = MapUtils.getIntValue(map, "pageSize", 20);
            if ((long) (pageNo - 1) * pageSize > list.size()) {
                list = new ArrayList<>();
            } else if ((long) (pageNo - 1) * pageSize < list.size() - pageSize) {
                list = list.subList((pageNo - 1) * pageSize, (pageNo - 1) * pageSize + pageSize);
            } else {
                list = list.subList((pageNo - 1) * pageSize, list.size());
            }
            return list;
        }

    }


    //XCEC CCEC公用 用户报修附近服务站列表
    @Transactional
    @Override
    public ModelAndView getXCECAllServiceStation(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        try {
            JSONObject obj = new JSONObject();   //返给手机端数据容器
            if (!map.containsKey("PositionLon")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "经度不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            if (!map.containsKey("PositionLat")) {
                obj.put("data", "");
                obj.put("status", 1);
                obj.put("msg", "纬度不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            int pageNo = MapUtils.getIntValue(map, "pageNo", 1);
            int pageSize = MapUtils.getIntValue(map, "pageSize", 20);
            float positionLon = Float.parseFloat(map.get("PositionLon").toString());
            float positionLat = Float.parseFloat(map.get("PositionLat").toString());
            String stationName = MapUtils.getString(map, "stationName", "");
            long companyId = MapUtils.getLong(map, "companyId", 4L);   //之前这个接口是给xcec使用的    为了前端改动少些    这里默认渠道xcec
            List<Map<String, Object>> serviceStationList = allServiceStationDao.getXCECServiceStationList(pageNo, pageSize, positionLat, positionLon, stationName, companyId);
            if (CollectionUtils.isNotEmpty(serviceStationList)) {
                for (Map<String, Object> serviceStation : serviceStationList) {
                    String ssType = serviceStation.get("SSType").toString();
                    String[] ssTypeSZ = new String[1];
                    if ("1".equals(ssType)) {
                        ssTypeSZ[0] = "维护保养";
                    } else if ("2".equals(ssType)) {
                        ssTypeSZ[0] = "保养及外围件维修";
                    } else if ("3".equals(ssType)) {
                        ssTypeSZ[0] = "全职";
                    } else {
                        ssTypeSZ[0] = "";
                    }
                    String[] ssLevelSZ = new String[1];
                    ssLevelSZ[0] = "其他";
                    serviceStation.put("SSType", ssTypeSZ);
                    serviceStation.put("SSLevel", ssLevelSZ);
                    //截取距离   保留小数点后一位
                    String distance = serviceStation.get("distance").toString();
                    distance = distance.substring(0, distance.indexOf(".") + 2) + "km";
                    serviceStation.put("distance", distance);
                }
            }
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("threeServiceStationList", serviceStationList);
            obj.put("data", returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception e) {
            ParameterTool.writeErrorResponse(response);
            //主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
